package com.auto.base.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

/**
 * Created by YuanWei1 on 2025/6/17.
 *
 * Description:
 */
abstract class BaseViewModel : ViewModel() {
    private val _uiEvent = Channel<UiEvent>(Channel.BUFFERED)
    val uiEvent = _uiEvent.receiveAsFlow()

    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading

    protected fun sendUiEvent(event: UiEvent) {
        viewModelScope.launch { _uiEvent.send(event) }
    }

    protected fun showToast(message: String) = sendUiEvent(UiEvent.Toast(message))
    protected fun setLoading(loading: Boolean) {
        _isLoading.value = loading
    }

    protected fun launchWithHandler(
        showLoading: Boolean = true,
        onError: ((Throwable) -> Unit)? = null,
        block: suspend () -> Unit
    ) {
        viewModelScope.launch {
            if (showLoading) setLoading(true)
            try {
                block()
            } catch (e: Exception) {
                handleException(e)
                onError?.invoke(e)
            } finally {
                if (showLoading) setLoading(false)
            }
        }
    }

    protected open fun handleException(e: Throwable) {
        e.printStackTrace()
        showToast(e.message ?: "Unknown Error")
    }
}

// 📁 base/UiEvent.kt
sealed class UiEvent {
    data class Toast(val message: String) : UiEvent()
    data class NavigateTo(val route: String) : UiEvent()
    object NavigateBack : UiEvent()
}